package cn.edu.hitsz.compiler.asm;

import cn.edu.hitsz.compiler.ir.Instruction;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class AsmCode
{
    static private String[] reg = new String[]{"t0", "t1", "t2", "t3", "t4", "t5", "t6", "a0", "x0"};
    public static String add(int rd, int rs1, int rs2)
    {
        return  "   " + "add " + reg[rd] + ", " + reg[rs1] + ", " + reg[rs2];
    }
    public static List<String> addi(int rd, int rs1, int imm)
    {
        if (imm > 2047 || imm < -2048) //超出立即数范围
            return List.of(li(6, imm), add(rd, rs1, 6));
        else
            return  List.of("   " + "addi " + reg[rd] + ", " + reg[rs1] + ", " + imm);
    }
    public static String sub(int rd, int rs1, int rs2)
    {
        return  "   " + "sub " + reg[rd] + ", " + reg[rs1] + ", " + reg[rs2];
    }
    public static String mul(int rd, int rs1, int rs2)
    {
        return  "   " + "mul " + reg[rd] + ", " + reg[rs1] + ", " + reg[rs2];
    }
    public static String div(int rd, int rs1, int rs2)
    {
        return  "   " + "div " + reg[rd] + ", " + reg[rs1] + ", " + reg[rs2];
    }
    public static String li(int rd, int imm)
    {
        return  "   " + "li " + reg[rd] + ", " + imm;
    }
    public static String mv(int rd, int rs)
    {
        return  "   " + "mv " + reg[rd] + ", " + reg[rs];
    }
    public static String neg(int rd, int rs)
    {
        return  "   " + "neg " + reg[rd] + ", " + reg[rs];
    }

    public static String lui(int rd, int imm)
    {
        return "    " + "lui" + reg[rd] + "," + imm;
    }
    public static String lw(int rd, int rs1, int offset)
    {
        return "   " + "lw " + reg[rd] + ", " + offset + "(" + reg[rs1] + ")";
    }
    public static List<String> lw(int rd, int offset)
    {
        if (offset > 2047 || offset < -2048) //超出立即数范围
            return List.of(lui(6, offset>>12), lw(rd, 6, offset & 0x0fff));
        else
            return List.of(lw(rd, 8, offset));
    }
    public static String sw(int rs2, int rs1, int offset)
    {
        return "   " + "sw " + reg[rs2] + ", " + offset + "(" + reg[rs1] + ")";
    }
    public static List<String> sw(int rs2, int offset)
    {
        if (offset > 2047 || offset < -2048) //超出立即数范围
            return List.of(lui(6, offset>>12), sw(rs2, 6, offset & 0x0fff));
        else
            return List.of(sw(rs2, 8, offset));
    }
}
